package dogapm

import (
	"context"
	"github.com/sirupsen/logrus"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
	"time"
)

const (
	traceId = "trace_id"
)

type log struct {
}

func init() {
	logrus.SetFormatter(&logrus.JSONFormatter{})
}

func (l *log) Info(ctx context.Context, action string, kv map[string]any) {
	kv["action"] = action
	logrus.WithFields(kv).Infoln()
}
func (l *log) Warn(ctx context.Context, action string, kv map[string]any) {
	kv["action"] = action
	logrus.WithFields(kv).Warnln()
}
func (l *log) Debug(ctx context.Context, kv map[string]any, action string) {
	kv["action"] = action
	logrus.WithFields(kv).Debugln()
}
func (l *log) Error(ctx context.Context, action string, kv map[string]any, err error) {
	kv["action"] = action
	logrus.WithFields(kv).Errorln()
	if span := trace.SpanFromContext(ctx); span != nil {
		kv[traceId] = span.SpanContext().TraceID().String()
		span.SetAttributes(attribute.Bool("error", true))
		span.RecordError(err, trace.WithStackTrace(true), trace.WithTimestamp(time.Now()))
	}
}

var Logger = &log{}
